package ycl.base.common.base.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import ycl.base.common.base.entity.BaseEntity;
import ycl.base.common.base.mapper.BaseDao;
import ycl.base.common.base.service.BaseService;
import ycl.base.common.constants.HtmlConstant;
import ycl.base.common.constants.RedisConstant;
import ycl.base.common.models.base.PageParams;
import ycl.base.common.models.base.QueryPage;
import ycl.base.common.models.res.login.LoginRes;
import ycl.base.common.utils.RedisOperationUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 逻辑层基类处理
 *
 * @author: YCL
 * @date: 2021-06-05 00:00:33
 */
@Service
@Lazy
public abstract class BaseServiceImpl<M extends BaseDao<T>, T extends BaseEntity>
		extends ServiceImpl<M, T>
		implements BaseService<T> {

	@Resource
	private RedisOperationUtil redisOperationUtil;
	@Resource
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private BaseDao<T> baseDao;

	@Override
	@SuppressWarnings("all")
	public boolean isLogin(HttpServletRequest request){
		String token = request.getHeader(HtmlConstant.TOKEN);
		if (StrUtil.isBlank(token))
			return false;
		String key = RedisConstant.USER_LOGIN + token;
		String value = stringRedisTemplate.opsForValue().get(key);
		if (StrUtil.isBlank(value))
			return false;
		return true;
	}

	@Override
	public LoginRes getLoginUser(HttpServletRequest request) {
		return redisOperationUtil.getLoginUser(request);
	}

	@Override
	public LoginRes getLoginUserNotThrow(HttpServletRequest request) {
		LoginRes user = redisOperationUtil.getLoginUser(request, false);
		return user == null ? new LoginRes() : user;
	}

	@Override
	public Long getLoginUserId(HttpServletRequest request) {
		return getLoginUser(request).getId();
	}

	@Override
	public Long getLoginUserIdNotThrow(HttpServletRequest request) {
		return getLoginUserNotThrow(request).getId();
	}


	@Override
	public QueryPage<T> findPage(PageParams params, T query) {
		Page<T> page = new Page<>(params.getCurrent(), params.getSize());
		List<T> list = baseDao.findPage(page, query);
		page.setRecords(list);
		return new QueryPage<>(page);
	}
}
